<template>
  <a-card :bordered="false" :class="'cust-erp-sub-tab'">
    <!-- 操作按钮区域 -->
    <div class="table-operator" v-if="mainId">
      <a-button @click="handleAdd" type="primary" icon="plus" v-show="!isChecked">新增</a-button>
      <a-dropdown v-if="selectedRowKeys.length > 0 && !isChecked">
        <a-menu slot="overlay">
          <a-menu-item key="1" @click="batchDel"><a-icon type="delete" />删除</a-menu-item>
        </a-menu>
        <a-button style="margin-left: 8px"> 批量操作 <a-icon type="down"/></a-button>
      </a-dropdown>
    </div>

    <!-- table区域-begin -->
    <div>
      <a-table
        ref="table"
        size="middle"
        bordered
        rowKey="id"
        :indentSize="50"
        :scroll="{ x: true }"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="false"
        :loading="loading"
        :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
        @change="handleTableChange"
      >
        <template slot="materialCode" slot-scope="text, record">
          <a-select
            :dropdownMatchSelectWidth="false"
            :showSearch="true"
            style="width: 100%"
            :value="selectValue"
            :maxTagCount="10"
            @search="searchMaterial"
            @blur="clearMaterialData"
            @focus="searchMaterial"
            @select="changeRecord($event, record)"
            @popupScroll="popupScroll"
            :filter-option="false"
            v-if="record.selectable"
          >
            <a-select-option v-for="(item, index) in materialData" :key="index">
              <span v-for="(i, index) in materialField" :key="index">
                {{ item[i] }}
                <a-divider type="vertical" style="background-color: #0c8fcf"></a-divider>
              </span>
            </a-select-option>
          </a-select>
          <template v-else slot-scope="text, record">
            {{ record.materialCode }}
          </template>
        </template>

        <template slot="number" slot-scope="text, record">
          <a-input-number v-model:value="record.num" v-if="record.selectable"></a-input-number>
          <span v-else>{{ text }}</span>
        </template>

        <template slot="wastageRate" slot-scope="text, record">
          <a-input-number
            v-model:value="record.wastageRate"
            v-if="record.selectable"
            :formatter="val => `${val}%`"
          ></a-input-number>
          <span v-else>{{ text }}%</span>
        </template>

        <template slot="warehouse" slot-scope="text, record">
          <j-search-select-tag
            style="width: 120px;"
            v-model:value="record.warehouse"
            v-if="record.selectable"
            dict="hf_warehouse,warehouse_name,id"
          ></j-search-select-tag>
          <span v-else>{{ text }}</span>
        </template>

        <template slot="action" slot-scope="text, record">
          <div class="editable-row-operations" v-show="record.status !== 1">
            <span v-if="record.editable">
              <a @click="() => save(record)">保存</a>
              <a-divider type="vertical" style="background-color: grey"></a-divider>
              <a @click="() => cancel(record)">取消</a>
            </span>
            <span v-else>
              <a :disabled="editingKey !== ''" @click="edit(record)" v-show="!isChecked">编辑</a>
              <a-divider type="vertical" style="background-color: grey" v-show="!isChecked"></a-divider>
              <a :disabled="editingKey !== ''" @click="handleDelete(record.id)" v-show="!isChecked">删除</a>
            </span>
          </div>
        </template>
      </a-table>
    </div>
  </a-card>
</template>

<script>
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import { getAction, postAction, putAction } from '@api/manage'
import { HfIODetailMixin } from '@/mixins/HfIODetailMixin'

export default {
  name: 'HfBomDetailList',
  mixins: [JeecgListMixin, HfIODetailMixin],
  components: {},
  props: {
    mainId: {
      type: String,
      default: '',
      required: false
    }
  },
  watch: {
    mainId: {
      immediate: true,
      handler(val) {
        if (!this.mainId) {
          this.clearList()
        } else {
          this.queryParam['hfBomId'] = val
          this.mainId = val
          this.loadData(1)
        }
      }
    }
  },
  data() {
    return {
      description: 'bom单信息管理页面',
      disableMixinCreated: true,
      isChecked: false,
      // 表头
      columns: [
        {
          title: '#',
          dataIndex: '',
          key: 'rowIndex',
          width: 60,
          align: 'center',
          customRender: function(t, r, index) {
            return parseInt(index) + 1
          }
        },
        {
          title: '物料代码',
          align: 'center',
          dataIndex: 'materialCode',
          scopedSlots: { customRender: 'materialCode' }
        },
        {
          title: '物料名称',
          align: 'center',
          dataIndex: 'materialName'
        },
        {
          title: '规格型号',
          align: 'center',
          dataIndex: 'sap'
        },
        {
          title: '单位',
          align: 'center',
          dataIndex: 'unit_dictText'
        },
        {
          title: '标准用量',
          align: 'center',
          dataIndex: 'number',
          scopedSlots: { customRender: 'number' }
        },
        {
          title: '损耗率',
          align: 'center',
          dataIndex: 'wastageRate',
          scopedSlots: { customRender: 'wastageRate' }
        },
        {
          title: '发料仓库',
          align: 'center',
          dataIndex: 'warehouse_dictText',
          scopedSlots: { customRender: 'warehouse' }
        },
        {
          title: '操作',
          dataIndex: 'action',
          align: 'center',
          fixed: 'right',
          width: 147,
          scopedSlots: { customRender: 'action' }
        }
      ],
      url: {
        list: '/material/hfBom/listHfBomDetailByMainId',
        delete: '/material/hfBom/deleteHfBomDetail',
        deleteBatch: '/material/hfBom/deleteBatchHfBomDetail',
        exportXlsUrl: '/material/hfBom/exportHfBomDetail',
        importUrl: '/material/hfBom/importHfBomDetail',
        add: '/material/hfBom/addHfBomDetail',
        edit: '/material/hfBom/editHfBomDetail'
      },
      dictOptions: {},
      isorter: {
        column: 'materialCode',
        order: 'asc'
      }
    }
  },
  created() {},
  computed: {
    importExcelUrl() {
      return `${window._CONFIG['domianURL']}/${this.url.importUrl}/${this.mainId}`
    }
  },
  methods: {
    clearList() {
      this.dataSource = []
      this.selectedRowKeys = []
      this.ipagination.current = 1
    },
    loadData(arg) {
      if (!this.url.list) {
        this.$message.error('请设置url.list属性!')
        return
      }
      //加载数据 若传入参数1则加载第一页的内容
      if (arg === 1) {
        this.ipagination.current = 1
      }
      let params = this.getQueryParams() //查询条件
      this.loading = true
      getAction(this.url.list, params)
        .then(res => {
          if (res.success) {
            //update-begin---author:zhangyafei    Date:20201118  for：适配不分页的数据列表------------
            this.dataSource = res.result.records || res.result

            if (res.result.total) {
              this.ipagination.total = res.result.total
            } else {
              this.ipagination.total = 0
            }
            //update-end---author:zhangyafei    Date:20201118  for：适配不分页的数据列表------------
          } else {
            this.$message.warning(res.message)
          }
        })
        .finally(() => {
          this.loading = false
        })
    },
    /**
     * 修改表格的单元格数据
     * @param index 当前数据在filterData中的索引
     * @param record 当前行数据
     */
    changeRecord(index, record) {
      //获取物料信息
      const newData = [...this.dataSource]
      //找到选中行的数据
      const target = this.materialData[index]
      //找到当前行的数据
      const current = newData.find((item, index) => {
        return record.id === item.id
      })
      Object.keys(target).forEach(key => {
        if (target[key] === null) {
          target[key] = ''
        }
      })
      //设置数据
      current.materialId = target.id
      current.materialCode = target.materialCode
      current.materialName = target.materialName
      current.sap = target.sap
      current.unit_dictText = target.unit_dictText
      current.unit = target.unit
      current.materialType_dictText = target.materialType_dictText
      current.materialType = target.materialType
      this.selectValue = target.materialCode
      this.editingKey = ''
      this.dataSource = newData
    },
    save(record) {
      if (record.num === null || record.num === undefined) {
        this.$message.error('请输入数量')
        return
      }
      let param = Object.assign({}, record)
      param['hfBomId'] = this.mainId
      this.loading = false
      if (param.add) {
        postAction(this.url.add, param)
          .then(res => {
            if (res.success) {
              this.$message.success(res.message)
              this.loadData()
            } else {
              this.$message.warning(res.message)
            }
          })
          .finally(() => {
            this.loading = true
          })
      } else {
        putAction(this.url.edit, param)
          .then(res => {
            if (res.success) {
              this.$message.success(res.message)
              this.loadData()
            } else {
              this.$message.warning(res.message)
            }
          })
          .finally(() => {
            this.loading = true
            this.selectValue = ''
          })
      }
    }
  }
}
</script>
<style scoped>
@import '~@assets/less/common.less';
</style>
